package cn.com.homeyoda.aimate.aihealth.ui.questionnaire;

import static cn.com.homeyoda.aimate.aihealth.utils.AppConstants.ID;
import static cn.com.homeyoda.aimate.aihealth.utils.AppConstants.SUBMIT_QUESTIONNAIRE_ANSWER;
import static cn.com.homeyoda.aimate.aihealth.utils.AppConstants.TITLE;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.LinearLayout;

import androidx.core.content.ContextCompat;
import androidx.lifecycle.ViewModelProviders;

import com.google.android.flexbox.FlexboxLayout;
import com.google.android.material.button.MaterialButton;
import com.jeremyliao.liveeventbus.LiveEventBus;
import com.wzq.mvvmsmart.utils.ToastUtils;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;

import cn.com.homeyoda.aimate.aihealth.BR;
import cn.com.homeyoda.aimate.aihealth.R;
import cn.com.homeyoda.aimate.aihealth.app.AppViewModelFactory;
import cn.com.homeyoda.aimate.aihealth.base.BaseActivity;
import cn.com.homeyoda.aimate.aihealth.bean.QuestionnaireAnswerBean;
import cn.com.homeyoda.aimate.aihealth.bean.QuestionnaireOptionBean;
import cn.com.homeyoda.aimate.aihealth.bean.QuestionnaireTopicBean;
import cn.com.homeyoda.aimate.aihealth.databinding.ActivityQuestionnaireTopicBinding;

public class QuestionnaireTopicActivity extends BaseActivity<ActivityQuestionnaireTopicBinding, QuestionnaireTopicViewModel> implements View.OnClickListener {

    private String id;
    private int currentTopic = 0;
    private boolean isSingleSelection = true;
    private final List<QuestionnaireTopicBean> topicList = new ArrayList<>();
    private final List<QuestionnaireOptionBean> optionList = new ArrayList<>();

    // 存放问题的index和选项的id
    private final Map<Integer, Set<String>> topicMap = new HashMap<>();

    public static void start(Context context, String id, String title) {
        Intent starter = new Intent(context, QuestionnaireTopicActivity.class);
        starter.putExtra(ID, id);
        starter.putExtra(TITLE, title);
        context.startActivity(starter);
    }

    @Override
    public QuestionnaireTopicViewModel initViewModel() {
        AppViewModelFactory factory = AppViewModelFactory.getInstance(getApplication());
        return ViewModelProviders.of(this, factory).get(QuestionnaireTopicViewModel.class);
    }

    @Override
    public int initContentView(Bundle savedInstanceState) {
        return R.layout.activity_questionnaire_topic;
    }

    @Override
    public int initVariableId() {
        return BR.viewModel;
    }

    @Override
    public void initData() {
        super.initData();
        id = getIntent().getStringExtra(ID);
        viewModel.getQuestionnaireTopicData(id);
        String title = getIntent().getStringExtra(TITLE);
        binding.tvTitle.setText(title);
        initView();
    }

    private void initView() {
        binding.titleBar.ivBack.setOnClickListener(this);
        binding.btnPre.setOnClickListener(this);
        binding.btnNext.setOnClickListener(this);
        binding.titleBar.tvTitle.setText(getString(R.string.questionnaires));
        initOptionView();
    }

    private void setTopicView() {
        if (topicList.isEmpty() || topicList.size() <= currentTopic) return;
        QuestionnaireTopicBean topic = topicList.get(currentTopic);
        isSingleSelection = "1".equals(topic.getType());
        binding.tvChoiceType.setText(getString(isSingleSelection ? R.string.radio : R.string.multiple_choices));
        viewModel.getQuestionnaireOptionData(topic.getId());
        updateSegmentProgress();
    }

    private void setOptionView() {
        int size = optionList.size();
        if (size > 0) {
            QuestionnaireOptionBean bean = optionList.get(0);
            binding.option1.setText(bean.getDescribe());
            binding.option1.setTag(bean.getId());
        }
        if (size > 1) {
            QuestionnaireOptionBean bean = optionList.get(1);
            binding.option2.setText(bean.getDescribe());
            binding.option2.setTag(bean.getId());
        }
        if (size > 2) {
            QuestionnaireOptionBean bean = optionList.get(2);
            binding.option3.setText(bean.getDescribe());
            binding.option3.setTag(bean.getId());
        }
        if (size > 3) {
            QuestionnaireOptionBean bean = optionList.get(3);
            binding.option4.setText(bean.getDescribe());
            binding.option4.setTag(bean.getId());
        }
    }

    private void updateSegmentProgress() {
        LinearLayout segmentContainer = findViewById(R.id.segment_container);

        int total = topicList.size();
        Set<String> curtSelectedSet = topicMap.get(currentTopic);
        int current = curtSelectedSet == null || curtSelectedSet.isEmpty() ? currentTopic : currentTopic + 1;
        double progress = ((double) current / total) * 10;
        binding.tvProgress.setText(current + "/" + total);
        binding.btnNext.setText(getString(current >= topicList.size() ? R.string.submit : R.string.next_question));

        segmentContainer.removeAllViews();

        int margin = 9;
        int width = (segmentContainer.getWidth() - (total - 1) * margin) / total;
        for (int i = 1; i <= total; i++) {
            View segmentView = new View(this);

            LinearLayout.LayoutParams layoutParams = new LinearLayout.LayoutParams(width, 26);

            // 设置每个 segment 的右边距（除了最后一个）
            if (i != total) {
                layoutParams.setMarginEnd(margin);
            }

            segmentView.setLayoutParams(layoutParams);

            // 设置背景：当前进度为亮蓝色，其余为淡蓝色
            if (i <= progress) {
                segmentView.setBackground(ContextCompat.getDrawable(this, R.drawable.bg_segment_active));
            } else {
                segmentView.setBackground(ContextCompat.getDrawable(this, R.drawable.bg_segment_inactive));
            }

            segmentContainer.addView(segmentView);
        }
    }

    @Override
    public void initViewObservable() {
        super.initViewObservable();
        viewModel.questionnaireTopicData.observe(this, list -> {
            topicList.clear();
            topicList.addAll(list);
            setTopicView();
        });

        viewModel.questionnaireOptionData.observe(this, list -> {
            optionList.clear();
            optionList.addAll(list);
            if (list.isEmpty()) return;
            setOptionView();
            restorePreviousSelection();
        });

        LiveEventBus.get(SUBMIT_QUESTIONNAIRE_ANSWER, Boolean.class).observe(this, aBoolean -> {
            QuestionnaireCompleteActivity.start(this);
            finish();
        });
    }

    @Override
    public void onClick(View v) {
        int vId = v.getId();
        if (vId == R.id.iv_back) {
            finish();
        } else if (vId == R.id.btn_pre) {
            if (currentTopic <= 0) {
                return;
            }
            currentTopic--;
            setTopicView();
        } else if (vId == R.id.btn_next) {
            Set<String> curtSelectedSet = topicMap.get(currentTopic);
            if (curtSelectedSet == null || curtSelectedSet.isEmpty()) {
                ToastUtils.showShort("请选择您的回答");
                return;
            }
            if (currentTopic >= topicList.size() - 1) {
                List<String> ids = new ArrayList<>();
                for (Set<String> set : topicMap.values()) {
                    ids.addAll(set);
                }
                QuestionnaireAnswerBean answerBean = new QuestionnaireAnswerBean();
                answerBean.setId(id);
                answerBean.setIds(ids);
                viewModel.submitQuestionnaireAnswer(answerBean);
                return;
            }
            currentTopic++;
            setTopicView();
            Set<String> selectedSet = topicMap.get(currentTopic);
            if (selectedSet == null) {
                clearSelection();
            }
        }
    }

    private void restorePreviousSelection() {
        Set<String> selectedSet = topicMap.get(currentTopic);
        if (selectedSet == null) {
            return;
        }
        for (int i = 0; i < binding.flexboxLayout.getChildCount(); i++) {
            View child = binding.flexboxLayout.getChildAt(i);
            if (child instanceof MaterialButton) {
                MaterialButton button = (MaterialButton) child;
                Object tag = button.getTag();
                if (tag instanceof String){
                    button.setChecked(selectedSet.contains(tag.toString()));
                }
            }
        }
    }

    private void clearSelection() {
        for (int i = 0; i < binding.flexboxLayout.getChildCount(); i++) {
            View child = binding.flexboxLayout.getChildAt(i);
            if (child instanceof MaterialButton) {
                ((MaterialButton) child).setChecked(false);
            }
        }
    }

    private void initOptionView() {
        FlexboxLayout flexboxLayout = findViewById(R.id.flexboxLayout);

        for (int i = 0; i < flexboxLayout.getChildCount(); i++) {
            View child = flexboxLayout.getChildAt(i);
            if (child instanceof MaterialButton) {
                child.setOnClickListener(view -> {
                    Set<String> selectedSet = topicMap.get(currentTopic);
                    if (selectedSet == null) {
                        selectedSet = new HashSet<>();
                    }
                    if (isSingleSelection) {
                        // 单选
                        for (int j = 0; j < flexboxLayout.getChildCount(); j++) {
                            View btn = flexboxLayout.getChildAt(j);
                            if (btn instanceof MaterialButton) {
                                MaterialButton button = (MaterialButton) btn;
                                button.setChecked(btn == view); // 只允许当前点击的按钮被选中
                                String tag = (String) button.getTag();
                                if (button.isChecked()) {
                                    selectedSet.add(tag);
                                } else {
                                    selectedSet.remove(tag);
                                }
                            }
                        }
                    } else {
                        // 多选
                        MaterialButton button = (MaterialButton) view;
                        String tag = (String) button.getTag();
                        if (button.isChecked()) {
                            selectedSet.add(tag);
                        } else {
                            selectedSet.remove(tag);
                        }
                    }
                    topicMap.put(currentTopic, selectedSet);
                    updateSegmentProgress();
                });
            }
        }
    }

}